{% extends 'live/live_base.html' %}
{% load static %}

{% block title %}
    Jvhub直播:{{ lr.name }}
{% endblock %}

{% block css %}
    <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.11.0/skins/default/aliplayer-min.css"
          xmlns:xlink=""/>
    <script type="text/javascript" charset="utf-8"
            src="https://g.alicdn.com/de/prismplayer/2.11.0/aliplayer-min.js"></script>
{% endblock %}

{% block content %}
    {% if request.user == lr.user and lr.is_open %}
        <div class="container-fluid">
            <div class="row">
                <div class="col-12 text-center">
                    <div class="alert alert-warning d-flex align-items-center justify-content-center" role="alert">
                        <i class="bi bi-exclamation-triangle"></i>
                        <div>
                            点击<a class="alert-link" data-toggle="modal"
                                    data-target="#closeLiveModal">关闭直播</a>

                            <!-- Modal -->
                            <div class="modal fade" id="closeLiveModal" tabindex="-1" aria-labelledby="exampleModalLabel"
                                 aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">关闭直播</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body text-danger">
                                            确定关闭直播哦！！
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭
                                            </button>
                                            <button type="button" class="btn btn-danger" onclick="closeLive()">确定关闭直播</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    {% endif %}
    <div class="container-fluid">
        <div class="row justify-content-center">
            {#  直播画面 #}
            <div class="col-8">
                {#                头#}
                <div class="row" style="margin-bottom: 10px">
                    <div class="col-auto">
                        <div class="media">
                            <a href="{% url 'detail_user' %}?username={{ lr.user.username }}">
                                <img src="{{ MEDIA_URL }}{{ lr.user.image }}" class="mr-3"
                                     style="width:  64px; height: 64px;border-radius: 10px">
                            </a>
                            <div class="media-body">
                                <b class="mt-0" style="font-size: 20px">{{ lr.name }}</b>
                                <p><a href="{% url 'detail_user' %}?username={{ lr.user.username }}" class="text-decoration-none text-dark" target="_blank">{{ lr.user }}</a>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="prism-player text-center " id="player-con" style="width:100%;height: 700px">
                        <div style="margin-top: 350px;">
                            <b id="error-message" class="col-auto" style="color: white; font-size: 20px">
                                {% if not play_stream %}
                                    主播正在赶来的路上
                                {% endif %}
                            </b>
                        </div>
                    </div>
                </div>
            </div>

            {#   右侧 #}
            <div class="col-2">
                {# 榜单#}
                <div class="row" style="width: 100%;margin-left: 1px;margin-bottom: 10px">
                    <div class="col-auto">
                        <nav>
                            <div class="nav nav-tabs" id="nav-tab" role="tablist">
                                <a class="nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home"
                                   role="tab" aria-controls="nav-home" aria-selected="true">Home</a>
                                <a class="nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile"
                                   role="tab" aria-controls="nav-profile" aria-selected="false">Profile</a>
                                <a class="nav-link" id="nav-contact-tab" data-toggle="tab" href="#nav-contact"
                                   role="tab" aria-controls="nav-contact" aria-selected="false">Contact</a>
                            </div>
                        </nav>
                        <div class="tab-content  overflow-auto" id="nav-tabContent" style="height: 200px">
                            <div class="tab-pane fade show active" id="nav-home" role="tabpanel"
                                 aria-labelledby="nav-home-tab">...
                            </div>
                            <div class="tab-pane fade" id="nav-profile" role="tabpanel"
                                 aria-labelledby="nav-profile-tab">...
                            </div>
                            <div class="tab-pane fade" id="nav-contact" role="tabpanel"
                                 aria-labelledby="nav-contact-tab">...
                            </div>
                        </div>
                    </div>
                </div>

                {#  聊天室#}
                <div class="row overflow-auto" id="wrapper"
                     style="width: 100%;margin-left: 1px">
                    <div class="col-auto" style="height: 450px; width: 100%" id="talk-content">
                        <div class="row text-break text-monospace">
                            <span class="text-danger">
                                温馨提示:
                                <span style="background-color: gold">
                                    禁止传播封建迷信、吸烟酗酒、低俗色情、赌博诈骗等任何违法违规内容。请理性消费，如主播在直播时以不正当方式诱导打赏、私下交易，请谨慎判断，以防人身财产损失。请勿轻信各类招聘征婚、代练代抽、私下交易、购买礼包码、游戏币等广告信息，谨防网络诈骗。
                                </span>
                            </span>
                        </div>
                    </div>
                </div>

                {#                发送消息#}
                <div class="row" style="width: 100%;margin-left: 1px;margin-top: 10px">
                    <div class="col-8" style="height: 70px">
                        <div class="input-group">
                            <textarea id="comment_value" style="resize: none;border-radius: 10px" class="form-control"
                                      aria-label="With textarea" placeholder="请输入"></textarea>
                        </div>
                    </div>
                    <div class="col-4">
                        <button type="button" class="btn btn-primary" onclick="sendMessageLive()" id="sendMessageButton" style="height: 60px"
                                {% if not request.user.is_authenticated %}disabled{% endif %}>发送
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block custom_jss %}
    <script>
        function scrollToBottom() {
            const domWrapper = document.querySelector('#wrapper'); // 外层容器 出现滚动条的dom
            (function smoothscroll() {
                const currentScroll = domWrapper.scrollTop;   // 已经被卷掉的高度
                const clientHeight = domWrapper.offsetHeight; // 容器高度
                const scrollHeight = domWrapper.scrollHeight; // 内容总高度
                if (scrollHeight - 10 > currentScroll + clientHeight) {
                    window.requestAnimationFrame(smoothscroll);
                    domWrapper.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
                }
            })();
        }

        {#        聊天室websocket#}
        const ws_scheme_live = window.location.protocol === "https:" ? "wss" : "ws";
        const ws_path_live = ws_scheme_live + "://" + window.location.host + "/ws/live/" + '{{ lr.number }}' + "/";   //使用房间号当作组
        const live_ws = new WebSocket(ws_path_live);

        {% if request.user.is_authenticated %}
            function sendMessageLive() {
            let val = $('#comment_value').val();
                if (val === '') {
                    return
                }
            let data = {
                    'user': '{{ request.user.id }}',
                    'username': '{{ request.user.username }}',
                    'message': val,
                    'group_name': {{ lr.number }}
                };
            $.ajax({
                cache: false,
                type: "POST",
                url: "{% url 'live_send_message' %}",
                data: data,
                beforeSend: function (xhr, setting) {
                    $('#sendMessageButton').attr({disabled:"disabled"});
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    $('#comment_value').val('');
                },
                complete: function () {
                    $('#sendMessageButton').removeAttr('disabled');
                },
            })
        }
        {% endif %}

        live_ws.onmessage = function (event) {
            const data = JSON.parse(event.data);
            html = `<div class="row text-break text-monospace"><a class="text-decoration-none"  href="{% url 'detail_user' %}?username=${data['username']}">${data['nick_name']}</a>:&nbsp;${data['message']}</div>`;
            $('#talk-content').append(html);
            setTimeout(scrollToBottom, 100);
        };

        {#        关闭直播#}

        function closeLive() {
            $.ajax({
                type: 'POST',
                url: '{% url 'close_live' %}',
                dataType: 'json',
                async: true,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }

            })
        }

        {#aliplay播放器#}
        var player = new Aliplayer({
                "id": "player-con",
                "source": "{{ play_stream }}",
                "width": "100%",
                "height": "500px",
                "autoplay": true,
                "isLive": true,
                "rePlay": false,
                "playsinline": true,
                "isVBR": true,
                "preload": true,
                "controlBarVisibility": "hover",
                "useH5Prism": true,
                "skinLayout": [
                    {
                        "name": "bigPlayButton",
                        "align": "blabs",
                        "x": 30,
                        "y": 80
                    },
                    {
                        "name": "infoDisplay"
                    },
                    {
                        "name": "controlBar",
                        "align": "blabs",
                        "x": 0,
                        "y": 0,
                        "children": [
                            {
                                "name": "liveDisplay",
                                "align": "tlabs",
                                "x": 15,
                                "y": 6
                            },
                            {
                                "name": "fullScreenButton",
                                "align": "tr",
                                "x": 10,
                                "y": 10
                            },
                            {
                                "name": "volume",
                                "align": "tr",
                                "x": 5,
                                "y": 10
                            }
                        ]
                    }
                ]
            }, function (player) {
                console.log("The player is created");
            }
        );
        player.on('liveStreamStop', function () {
            $('#error-message').text('主播正在赶来的路上')
        });
    </script>
{% endblock %}